<template>
  <div class="app-container">
    <!-- 顶部筛选区域 -->
    <el-card class="search-card">
      <el-form :model="filterForm">
        <el-row :gutter="20">
          <el-col :span="4">
            <el-form-item label="搜索">
              <el-input v-model="filterForm.searchKey" placeholder="设备名称/工单号" clearable @keyup.enter="handleSearch" />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="时间范围">
              <el-date-picker v-model="filterForm.dateRange" type="daterange" range-separator="至"
                start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" @change="handleDateChange" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="工单状态">
              <el-select v-model="filterForm.maintenanceOrderStatus" placeholder="全部状态" clearable>
                <el-option v-for="item in statusOptions" :key="item.dictValue" :label="item.dictLabel"
                  :value="item.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" style="text-align: left">
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 工单表格 -->
    <el-card class="mt-1">
      <el-button type="primary" @click="showCreateDialog">新建工单</el-button>
      <el-table class="mt-2" :data="tableData" border style="width: 100%" v-loading="loading">
        <el-table-column prop="maintenanceOrderNumber" label="工单号" align="center" width="180" />
        <el-table-column prop="associatedEquipmentName" label="设备名称" align="center" />
        <el-table-column prop="maintenanceType" label="保养类型" align="center" >
          <template #default="{ row }">
            <el-tag >
              {{ getName( maintenanceTypeOptions,row.maintenanceType , 'dictValue','dictLabel' ) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="scheduledMaintenanceTime" label="计划时间" align="center" width="180" />
        <el-table-column prop="completionTime" label="完成时间" align="center" width="180">
          <template #default="{ row }">
            {{ row.completionTime || '--' }}
          </template>
        </el-table-column>
        <el-table-column prop="executor" label="负责人" align="center" >
          <template #default="{ row }">
            {{ getName( executorOptions,row.executor , 'id','name' ) }}
          </template>
        </el-table-column>
        <el-table-column prop="maintenanceOrderStatus" label="状态" align="center" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.maintenanceOrderStatus)">
              {{ formatStatus(row.maintenanceOrderStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="220" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="showDetailDialog(row)">查看</el-button>
            <el-button v-if="row.maintenanceOrderStatus === '0'" type="primary" size="small"
              @click="handleStartMaintenance(row)">开始保养</el-button>
            <el-button v-else-if="row.maintenanceOrderStatus === '1'" type="success" size="small"
              @click="handleFinishMaintenance(row)">完成保养</el-button>
            <el-button v-if="row.maintenanceOrderStatus === '0'" type="danger" size="small"
              @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination class="mt-2" v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </el-card>

    <!-- 新建工单对话框 -->
    <el-dialog v-model="createDialogVisible" title="新建保养工单" width="50%" :close-on-click-modal="false"
      @close="resetCreateForm">
      <el-form ref="createFormRef" :model="createForm" :rules="createRules" label-width="100px">
        <el-form-item label="关联设备" prop="associatedEquipmentId">
          <el-select v-model="createForm.associatedEquipmentId" placeholder="请选择设备" style="width: 100%" filterable>
            <el-option v-for="item in deviceOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="保养类型" prop="maintenanceType">
          <el-select v-model="createForm.maintenanceType" placeholder="请选择保养类型" style="width: 100%">
            <el-option v-for="item in maintenanceTypeOptions" :key="item.dictValue" :label="item.dictLabel"
              :value="item.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="计划时间" prop="scheduledMaintenanceTime">
          <el-date-picker v-model="createForm.scheduledMaintenanceTime" type="datetime" placeholder="选择计划时间"
            style="width: 100%" value-format="YYYY-MM-DD HH:mm:ss" />
        </el-form-item>
        <el-form-item label="负责人" prop="executor">
          <el-select v-model="createForm.executor" placeholder="请选择负责人" style="width: 100%" filterable>
            <el-option v-for="item in executorOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="检查项目">
          <div v-for="(item, index) in createForm.itemList" :key="index" class="inspection-item-form">
            <el-row :gutter="20">
              <el-col :span="10">
                <el-input v-model="item.itemName" placeholder="项目名称" />
              </el-col>
              <el-col :span="10">
                <el-input v-model="item.standardRequirement" placeholder="标准要求" />
              </el-col>
              <el-col :span="4">
                <el-button type="danger" @click="removeInspectionItem(index)" circle>
                  <el-icon>
                    <Minus />
                  </el-icon>
                </el-button>
              </el-col>
            </el-row>
          </div>
          <el-button type="primary" @click="addInspectionItem" plain class="" style="margin-left: 10px;">
            <el-icon>
              <Plus />
            </el-icon>
            添加检查项目
          </el-button>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="createForm.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitCreateForm">确认创建</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 工单详情对话框 -->
    <el-dialog v-model="detailDialogVisible" :title="'保养工单详情 - ' + currentOrder.maintenanceOrderNumber" width="70%"
      top="5vh">
      <div class="detail-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="工单号">{{ currentOrder.maintenanceOrderNumber }}</el-descriptions-item>
          <el-descriptions-item label="设备名称">{{ currentOrder.associatedEquipmentName }}</el-descriptions-item>
          <el-descriptions-item label="保养类型">
            <el-tag>
              {{ getName( maintenanceTypeOptions,currentOrder.maintenanceType , 'dictValue','dictLabel' ) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="计划时间">{{ currentOrder.scheduledMaintenanceTime }}</el-descriptions-item>
          <el-descriptions-item label="完成时间">{{ currentOrder.completionTime || '-' }}</el-descriptions-item>
          <el-descriptions-item label="负责人">{{ getName( executorOptions,currentOrder.executor , 'id','name' ) }}</el-descriptions-item>
          <el-descriptions-item label="工单状态">
            <el-tag :type="getStatusTagType(currentOrder.maintenanceOrderStatus)">
              {{ formatStatus(currentOrder.maintenanceOrderStatus) }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>

        <el-divider />

        <h3>检查项目</h3>
        <el-table :data="currentOrder.itemList" border style="width: 100%">
          <el-table-column prop="itemName" label="项目名称" align="center" />
          <el-table-column prop="standardRequirement" label="标准要求" align="center" />
          <el-table-column prop="isCompleted" label="完成状态" align="center" width="120">
            <template #default="{ row }">
              <el-tag :type="row.isCompleted === '1' ? 'success' : 'danger'">
                {{ row.isCompleted === '1' ? '已完成' : '未完成' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="solutionMeasures" label="处理意见" align="center" />
        </el-table>

        <el-divider />

        <h3>保养记录</h3>
        <el-timeline>
          <el-timeline-item v-for="(record, index) in currentOrder.recordList" :key="index"
            :timestamp="record.eventTime">
            {{ record.operatorName }} - {{ record.eventType }}
          </el-timeline-item>
        </el-timeline>

        <el-divider />

        <h3>处理意见</h3>
        <el-input v-model="currentOrder.solutionMeasures" type="textarea" :rows="3" readonly placeholder="无处理意见" />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 开始保养对话框 -->
    <el-dialog v-model="startDialogVisible" :title="'开始保养 - ' + currentOrder.maintenanceOrderNumber" width="60%"
      top="5vh">
      <div class="operation-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="设备名称">{{ currentOrder.associatedEquipmentName }}</el-descriptions-item>
          <el-descriptions-item label="保养类型">{{ getName( maintenanceTypeOptions,currentOrder.maintenanceType , 'dictValue','dictLabel' ) }}</el-descriptions-item>
          <el-descriptions-item label="计划时间">{{ currentOrder.scheduledMaintenanceTime }}</el-descriptions-item>
          <el-descriptions-item label="负责人">{{  currentOrder.executor }}</el-descriptions-item>
        </el-descriptions>

        <el-divider />

        <h3>检查项目</h3>
        <div v-for="(item, index) in operationItems" :key="index" class="inspection-item">
          <h4>{{ item.itemName }}</h4>
          <p>标准要求: {{ item.standardRequirement }}</p>
          <el-radio-group v-model="item.isCompleted" @change="handleItemStatusChange(item)">
            <el-radio label="1">完成</el-radio>
            <el-radio label="0">未完成</el-radio>
          </el-radio-group>
        </div>

        <el-divider />

        <h3>处理意见</h3>
        <el-input v-model="operationForm.solutionMeasures" type="textarea" :rows="3" placeholder="请输入处理意见" />

        <el-divider />

        <h3>上传附件</h3>
        <UploadFile  v-model:file-id="operationForm.fileId" :limit="1"  type="image" />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="startDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitStartMaintenance">确认提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Minus } from '@element-plus/icons-vue'
import UploadFile from '@/components/UploadFile'
import {
  getMaintenanceTypeList,
  getMaintenanceStatusList,
  getDeviceList,
  getMaintenanceList,
  getMaintenanceDetail,
  addMaintenance,
  startMaintenance,
  finishMaintenance,
  deleteMaintenance,
  getUserListNew
} from '@/api/prod_operate/device/manage/repair'

// 筛选表单
const filterForm = reactive({
  searchKey: '',
  dateRange: [],
  maintenanceOrderStatus: ''
})

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 分页控制
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})
const getName = (options, value,typeValue , typeLabel) => {
    
    return options.find(item => item[typeValue] == value)[typeLabel];
 
}
// 下拉选项数据
const maintenanceTypeOptions = ref([])
const statusOptions = ref([])
const deviceOptions = ref([])
const executorOptions = ref()

// 当前查看的工单
const currentOrder = ref({
  maintenanceOrderNumber: '',
  associatedEquipmentName: '',
  scheduledMaintenanceTime: '',
  maintenanceOrderStatus: '',
  completionTime: '',
  maintenanceType: '',
  executor: '',
  itemList: [],
  recordList: [],
  solutionMeasures: '',
  fileVo: null
})

// 操作表单
const operationForm = reactive({
  id: '',
  itemList: [],
  solutionMeasures: '',
  fileId: null,
})

// 操作项目列表
const operationItems = ref([])

// 文件列表
const fileList = ref([])

// 对话框控制
const createDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const startDialogVisible = ref(false)

// 新建工单表单
const createForm = reactive({
  associatedEquipmentId: '',
  maintenanceType: '',
  scheduledMaintenanceTime: '',
  executor: '',
  itemList: [
    { itemName: '', standardRequirement: '' }
  ],
  remark: ''
})

const createRules = {
  associatedEquipmentId: [
    { required: true, message: '请选择关联设备', trigger: 'change' }
  ],
  maintenanceType: [
    { required: true, message: '请选择保养类型', trigger: 'change' }
  ],
  scheduledMaintenanceTime: [
    { required: true, message: '请选择计划时间', trigger: 'change' }
  ],
  executor: [
    { required: true, message: '请选择负责人', trigger: 'change' }
  ]
}

const createFormRef = ref(null)

// 初始化数据
const initData = async () => {
  try {
    loading.value = true

    // 获取下拉选项数据
    const [
      typeRes,
      statusRes,
      deviceRes
    ] = await Promise.all([
      getMaintenanceTypeList(),
      getMaintenanceStatusList(),
      getDeviceList()
    ])

    maintenanceTypeOptions.value = typeRes.data
    statusOptions.value = statusRes.data
    deviceOptions.value = deviceRes.data

    

    const data = await getUserListNew()
    executorOptions.value = data.data;

    // 获取工单列表数据
    await fetchMaintenanceList()
  } catch (error) {
    console.error('初始化数据失败:', error)
    ElMessage.error('初始化数据失败')
  } finally {
    loading.value = false
  }
}

// 获取工单列表
const fetchMaintenanceList = async () => {
  try {
    loading.value = true

    const params = {
      searchKey: filterForm.searchKey,
      startTime: filterForm.dateRange?.[0] || '',
      endTime: filterForm.dateRange?.[1] || '',
      maintenanceOrderStatus: filterForm.maintenanceOrderStatus,
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize
    }

    const res = await getMaintenanceList(params)
    tableData.value = res.rows
    pagination.total = res.total
  } catch (error) {
    console.error('获取工单列表失败:', error)
    ElMessage.error('获取工单列表失败')
  } finally {
    loading.value = false
  }
}

// 获取工单详情
const fetchMaintenanceDetail = async (id) => {
  try {
    const res = await getMaintenanceDetail(id)
    currentOrder.value = res.data
  } catch (error) {
    console.error('获取工单详情失败:', error)
    ElMessage.error('获取工单详情失败')
  }
}

// 格式化状态显示
const formatStatus = (status) => {
  const statusMap = {
    '0': '待处理',
    '1': '处理中',
    '2': '已完成',
    '3': '已取消'
  }
  return statusMap[status] || status
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const typeMap = {
    '0': 'warning',
    '1': 'primary',
    '2': 'success',
    '3': 'info'
  }
  return typeMap[status] || ''
}

// 处理搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchMaintenanceList()
}

// 重置搜索
const resetSearch = () => {
  filterForm.searchKey = ''
  filterForm.dateRange = []
  filterForm.maintenanceOrderStatus = ''
  handleSearch()
}

// 日期范围变化
const handleDateChange = () => {
  handleSearch()
}

// 分页大小变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchMaintenanceList()
}

// 当前页变化
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchMaintenanceList()
}

// 显示新建工单对话框
const showCreateDialog = () => {
  createDialogVisible.value = true
}

// 添加检查项目
const addInspectionItem = () => {
  createForm.itemList.push({ itemName: '', standardRequirement: '' })
}

// 移除检查项目
const removeInspectionItem = (index) => {
  if (createForm.itemList.length > 1) {
    createForm.itemList.splice(index, 1)
  } else {
    ElMessage.warning('至少保留一个检查项目')
  }
}

// 提交新建工单表单
const submitCreateForm = async () => {
  try {
    await createFormRef.value.validate()

    // 过滤空检查项目
    const validItems = createForm.itemList.filter(
      item => item.itemName && item.standardRequirement
    )

    if (validItems.length === 0) {
      ElMessage.error('请至少添加一个有效的检查项目')
      return
    }

    const data = {
      ...createForm,
      itemList: validItems
    }

    await addMaintenance(data)
    ElMessage.success('工单创建成功')
    createDialogVisible.value = false
    fetchMaintenanceList()
  } catch (error) {
    console.error('创建工单失败:', error)
    if (error.message) {
      ElMessage.error(error.message)
    }
  }
}

// 重置新建表单
const resetCreateForm = () => {
  if (createFormRef.value) {
    createFormRef.value.resetFields()
  }
  createForm.itemList = [{ itemName: '', standardRequirement: '' }]
  createForm.remark = ''
}

// 显示详情对话框
const showDetailDialog = async (row) => {
  await fetchMaintenanceDetail(row.id)
  detailDialogVisible.value = true
}

// 处理开始保养
const handleStartMaintenance = async (row) => {
  await fetchMaintenanceDetail(row.id)
  operationForm.id = row.id
  operationItems.value = JSON.parse(JSON.stringify(currentOrder.value.itemList))
  startDialogVisible.value = true
}

// 处理项目状态变化
const handleItemStatusChange = (item) => {
  if (item.isCompleted === '1') {
    item.solutionMeasures = ''
  }
}

// 处理文件变化
const handleFileChange = (file, files) => {
  fileList.value = files
}

// 提交开始保养
const submitStartMaintenance = async () => {
  try {
    const data = {
      id: operationForm.id,
      itemList: operationItems.value,
      solutionMeasures: operationForm.solutionMeasures
      // fileId: 这里需要处理文件上传逻辑
    }

    await startMaintenance(data)
    ElMessage.success('保养已开始')
    startDialogVisible.value = false
    fetchMaintenanceList()
  } catch (error) {
    console.error('开始保养失败:', error)
    ElMessage.error('开始保养失败')
  }
}

// 处理完成保养
const handleFinishMaintenance = async (row) => {
  try {
    ElMessageBox.confirm('确定要完成此保养工单吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      await finishMaintenance({
        id: row.id,
        itemList: row.itemList
      })
      ElMessage.success('保养已完成')
      fetchMaintenanceList()
    })
  } catch (error) {
    console.error('完成保养失败:', error)
    if (error !== 'cancel') {
      ElMessage.error('完成保养失败')
    }
  }
}

// 处理删除工单
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除此保养工单吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteMaintenance(row.id)
      ElMessage.success('删除成功')
      fetchMaintenanceList()
    } catch (error) {
      console.error('删除工单失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 取消删除
  })
}

// 初始化
onMounted(() => {
  initData()
})
</script>

<style scoped lang="scss">

.mt-2 {
  margin-top: 20px;
}

.detail-content {
  padding: 15px;
}

.detail-content h3 {
  margin-bottom: 15px;
  color: #409eff;
}

.operation-content {
  padding: 15px;
}

.inspection-item-form {
  margin-bottom: 10px;
  padding: 10px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.inspection-item {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.inspection-item h4 {
  margin-bottom: 10px;
  color: #606266;
}

.inspection-item p {
  margin-bottom: 10px;
  color: #909399;
  font-size: 14px;
}
</style>